<template>
	<el-container>
		<el-aside v-loading="showGrouploading" width="200px">
			<el-container>
				<el-header>
					<el-input v-model="groupFilterText" placeholder="输入关键字进行过滤" clearable></el-input>
				</el-header>
				<el-main class="nopadding">
					<el-tree ref="group" class="menu" node-key="id" :data="group" :current-node-key="''"
						:highlight-current="true" :expand-on-click-node="false" :filter-node-method="groupFilterNode"
						@node-click="groupClick"></el-tree>
				</el-main>
			</el-container>
		</el-aside>
		<el-container>
			<el-header>
				<div class="left-panel">
					<el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
					<el-button type="primary" plain :disabled="selection.length == 0" @click="restPwd()">密码重置
					</el-button>
					<el-button type="primary" plain :loading="loading" :disabled="selection.length == 0"
						@click="multiplychangeRole">批量分配角色</el-button>
					<el-button type="primary" :loading="loading" :disabled="selection.length == 0"
						@click="pushMultiplyData">批量权限设置</el-button>
				</div>
				<div class="right-panel">
					<div style="display: flex">
						<el-input @keyup.enter="upsearch" style="margin-right:20px" v-model="search.staffPhone"
							placeholder="手机号" clearable></el-input>
						<el-input @keyup.enter="upsearch" style="margin-right:20px" v-model="search.realName"
							placeholder="真实姓名" clearable></el-input>
						<el-button style="margin-right:20px" type="primary" icon="el-icon-search"
							@click="upsearch"></el-button>
					</div>
				</div>
			</el-header>
			<el-main class="nopadding">
				<scTable ref="table" border :apiObj="apiObj" :params="params" stripe remoteSort remoteFilter
					@selection-change="selectionChange">
					<el-table-column type="selection" width="50" fixed="left"></el-table-column>

					<el-table-column align="center" label="真实名称" prop="realName" width="130" column-key="filterUserName"
						fixed="left"></el-table-column>
					<el-table-column align="center" label="账号" prop="staffName" width="130" sortable="custom"
						fixed="left"></el-table-column>
					<el-table-column align="center" label="组织" prop="orgName" width="130"></el-table-column>
					<el-table-column align="center" label="角色" prop="roleName" width="130"></el-table-column>
					<!-- <el-table-column align="center" label="当前角色" prop="currentRoleName" width="130"></el-table-column> -->
					<el-table-column align="center" label="邮箱" prop="staffEmail" width="150"
						sortable="custom"></el-table-column>
					<el-table-column align="center" label="性别" prop="staffSex" width="130">
						<template #default="scope">
							<span v-if="scope.row.staffSex == 0">男</span>
							<span v-if="scope.row.staffSex == 1">女</span>
						</template>
					</el-table-column>
					<!-- <el-table-column label="电话" prop="staffPhone" width="170" sortable="custom"></el-table-column> -->

					<el-table-column align="center" label="是否启用" prop="enable" width="130">
						<template #default="scope">
							<el-switch v-model="scope.row.enable" :loading="scope.row.$switch_status" :active-value="0"
								:inactive-value="1" @change="changeSwitch($event, scope.row)"></el-switch>
						</template>
					</el-table-column>

					<el-table-column label="操作" fixed="right" align="center" width="260">
						<template #default="scope">
							<el-button-group>
								<el-button text type="primary" size="small"
									@click="table_edit_power(scope.row, scope.$index)">权限设置
								</el-button>
								<el-button text type="primary" size="small"
									@click="table_show(scope.row, scope.$index)">查看
								</el-button>
								<el-button text type="primary" size="small"
									@click="table_edit(scope.row, scope.$index)">编辑
								</el-button>
								<el-button text type="primary" size="small" @click="changeRole(scope.row)">分配角色
								</el-button>
								<!-- <el-button text type="primary" size="small"
									@click="table_custo(scope.row, scope.$index)">分配客户</el-button> -->
							</el-button-group>
						</template>
					</el-table-column>
				</scTable>
			</el-main>
		</el-container>
	</el-container>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess"
		@closed="dialog.save = false"></save-dialog>
	<send-dialog v-if="dialog.send" ref="sendDialog" @success="handleSuccess"
		@closed="dialog.save = false"></send-dialog>
	<edit-dialog v-if="dialog.edit" ref="editDialog" @success="handleSuccess"
		@closed="dialog.edit = false"></edit-dialog>
	<multiply-assignRole v-if="dialog.multiplyAssignRole" ref="multiplyAssignRole" @success="handleSuccess"
		@closed="dialog.multiplyAssignRole = false"></multiply-assignRole>

	<el-drawer v-model="dialog.add" size="70%" :with-header="false" :direction="direction" :before-close="handleClose">
		<add ref="addDialog" @success="handleSuccess" @closed="closeds"></add>
	</el-drawer>
	<customer @success="handleSuccess" @closed="customerVisible = false" ref="customer" v-if="customerVisible">
	</customer>
	<el-drawer v-model="dialog.permission" :size="800" :title="permissionTitle" custom-class="drawerBG" direction="rtl"
		destroy-on-close>
		<permissionDialog v-if="dialog.permission" ref="permissionDialog" @success="handleSaveSuccess"
			@closed="dialog.permission = false"></permissionDialog>
	</el-drawer>
</template>

<script>
import add from './add_emp'
import sendDialog from './assignRole'
import editDialog from './edit'
import customer from "./customer.vue";
import multiplyAssignRole from "./multiplyAssignRole.vue";
import permissionDialog from './permission'

export default {
	name: 'staff',
	components: {
		add,
		sendDialog,
		editDialog,
		customer,
		multiplyAssignRole,
		permissionDialog
	},
	data() {
		return {
			dialog: {
				save: false,
				send: false,
				edit: false,
				add: false,
				multiplyAssignRole: false,
				permission: false
			},
			customerVisible: false,
			showGrouploading: false,
			groupFilterText: '',
			group: [],
			apiObj: this.$API.basic.staff.list,
			params: { orgId: 0 },
			roleOptions: [],
			selection: [],
			search: {},
			node: {},
			user: {},
		}
	},
	watch: {
		groupFilterText(val) {
			this.$refs.group.filter(val)
		}
	},

	async mounted() {
		var data = await this.$API.basic.home.info.get()
		if (data && data.code == '0') {
			this.user = data.data
		}
		await this.getGroup()
		this.$nextTick(() => {
			let datas = this.findNodeById(this.group, this.user.orgId)
			// this.user.orgId
			this.$refs.group.setCurrentKey(datas.id)
			this.groupClick(datas)
		})

	},
	async created() {
		var res = await this.$API.basic.role.list.post({ data: {} })
		if (res && res.code == '0') {
			this.roleOptions = res.data
		}

		console.log(this.roleOptions)
	},
	methods: {
		//添加
		add() {
			if (!this.node.data) {
				this.$message.warning('未选择组织')
				return false
			}
			this.dialog.add = true
			this.$nextTick(() => {
				this.$refs.addDialog.open('add').setData(this.node.data)
			})
		},
		//密码重置
		async restPwd() {
			console.log(this.selection)
			let data = []
			this.selection.forEach(item => {
				let obj = {
					staffNumber: item.staffNumber
				}
				data.push(obj)
			})
			var res = await this.$API.basic.staff.restPwd.post({ data: data })
			if (res && res.code == 0) {
				this.$message.success('密码重置成功')
			}
		},
		//分配角色
		changeRole(row) {
			this.dialog.send = true
			this.$nextTick(() => {
				this.$refs.sendDialog.open('send').resetData().setData(row, this.roleOptions, this.group)
			})
		},
		//编辑
		table_edit(row) {
			this.dialog.edit = true
			this.$nextTick(() => {
				this.$refs.editDialog.open('edit').setData(row)
			})
		},
		table_custo(row) {

			this.customerVisible = true
			this.$nextTick(() => {
				this.$refs.customer.open('customer').setData(row)
			})

		},
		//表格内开关
		async changeSwitch(val, row) {
			row.enable = row.enable === 1 ? 0 : 1
			row.$switch_status = true
			let data = {
				enable: val,
				staffNumber: row.staffNumber
			}
			var res = await this.$API.basic.staff.enable.post({ data: data })
			if (res && res.code == 0) {
				setTimeout(() => {
					delete row.$switch_status
					row.enable = val
					// console.log(typeof val, row)
					this.$message.success('操作成功')
				}, 500)
			}
		},

		//查看
		table_show(row) {
			this.dialog.edit = true
			this.$nextTick(() => {
				this.$refs.editDialog.open('show').setData(row)
			})
		},
		//删除
		async table_del(row, index) {
			var reqData = { id: row.id }
			var res = await this.$API.user.userDeleteById.post({ data: reqData })
			if (res.code === 0) {
				//这里选择刷新整个表格 OR 插入/编辑现有表格数据
				this.$refs.table.tableData.splice(index, 1)
				this.$message.success(res.data)
			}
		},
		//批量删除
		async batch_del() {
			this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			})
				.then(() => {
					const loading = this.$loading()
					this.selection.forEach((item) => {
						this.$refs.table.tableData.forEach((itemI, indexI) => {
							if (item.id === itemI.id) {
								this.$refs.table.tableData.splice(indexI, 1)
							}
						})
					})

					this.batch_delte()

					loading.close()
					// this.$message.success("操作成功")
				})
				.catch(() => { })
		},
		//批量删除接口
		async batch_delte() {
			const arr = []
			this.selection.forEach((item) => {
				var reqData = { id: item.id }
				arr.push(reqData)
			})
			// var reqData = {id: row.id}
			var res = await this.$API.user.userDelBatch.post({ data: arr })
			if (res && res.code === 0) {
				//这里选择刷新整个表格 OR 插入/编辑现有表格数据
				this.$message.success(res.data)
			}
		},
		//表格选择后回调事件
		selectionChange(selection) {
			this.selection = selection
		},
		closeds() {
			this.dialog.add = false
			this.$refs.table.reload(this.params)
		},
		//加载树数据
		async getGroup() {
			this.showGrouploading = true
			var res = await this.$API.basic.org.list.post({ dataa: {} })
			this.showGrouploading = false
			// var allNode = {id: '', label: '所有'}
			// res.data.unshift(allNode);
			this.group = res.data
			console.log(this.group)

		},
		findNodeById(nodes, targetId) {
			for (let i = 0; i < nodes.length; i++) {
				const node = nodes[i];
				if (node.id === targetId) {
					return node; // 找到目标节点
				}
				if (node.children) {
					const result = this.findNodeById(node.children, targetId);
					if (result) {
						return result; // 找到目标节点
					}
				}
			}
			return null; // 未找到目标节点
		},
		//树过滤
		groupFilterNode(value, data) {
			if (!value) return true
			return data.label.indexOf(value) !== -1
		},
		//树点击事件
		groupClick(data) {
			let orgIds = []
			orgIds.push(data.id)
			var node = this.$refs.group.getNode(data)
			this.node = node
			this.getTree(node.data, orgIds)
			this.params.orgIds = orgIds
			this.search.realName = ''
			this.search.staffPhone = ''
			this.params.realName = this.search.realName
			this.params.staffPhone = this.search.staffPhone
			this.$refs.table.reload(this.params)
			// 	   this.group.forEach(node => {
			//     node.isCurrent = node.id === data.id;
			//   });
		},
		getTree(node, orgIds) {
			if (node.children === null || node.children.length === 0) {
				orgIds.push(node.id)
			} else {
				orgIds.push(node.id)

				node.children.forEach((item) => {
					this.getTree(item, orgIds)
				})
			}
		},
		//搜索
		upsearch() {
			this.$refs.table.upData(this.search)
		},
		//本地更新数据
		handleSuccess(data, mode) {
			// if (mode === 'add') {
			// 	this.$refs.table.refresh()
			// } else if (mode === 'edit') {
			// 	this.$refs.table.refresh()
			// }
			// this.dialog.multiplyAssignRole = fale
			this.$refs.table.refresh()
		},
		multiplychangeRole(row) {
			this.dialog.multiplyAssignRole = true
			// let staffIds = this.selection.map((item) => {
			// 	return item.id
			// })
			this.$nextTick(() => {
				this.$refs.multiplyAssignRole.open('send').setData(this.selection, this.group)
			})
		},
		//权限设置
		table_edit_power(row) {
			this.permissionTitle = "权限设置"
			this.dialog.permission = true
			this.$nextTick(() => {
				this.$refs.permissionDialog.open(row, false)
			})
		},
		//本地更新数据
		handleSaveSuccess(data, mode) {
			this.dialog.permission = false
		},
		pushMultiplyData(row) {
			this.permissionTitle = "批量权限设置"
			this.dialog.permission = true
			this.$nextTick(() => {
				this.$refs.permissionDialog.open(this.selection, true)
			})
		}
	}
}
</script>

<style></style>
